{% extends 'base.html' %}
{% load static %}

{% block title %}
{% if file_obj %}
编辑文件 - {{ file_obj.file_name }}
{% else %}
创建新文件 - {{ code.title }}
{% endif %}
{% endblock %}

{% block extra_css %}
<link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-dark.min.css" rel="stylesheet">
<style>
/* 游戏化深色主题样式 */
.container-fluid {
    color: rgba(255, 255, 255, 0.9) !important;
}

.editor-container {
    border: 2px solid rgba(100, 150, 255, 0.5) !important;
    border-radius: 15px !important;
    overflow: hidden;
    background: linear-gradient(135deg, rgba(45, 55, 85, 0.3) 0%, rgba(35, 45, 75, 0.4) 100%) !important;
    backdrop-filter: blur(15px);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3), 0 0 20px rgba(100, 150, 255, 0.2);
}

.editor-header {
    background: linear-gradient(135deg, rgba(100, 150, 255, 0.8), rgba(0, 212, 255, 0.8)) !important;
    padding: 0.75rem 1rem;
    border-bottom: 1px solid rgba(255, 255, 255, 0.2) !important;
    display: flex;
    justify-content: between;
    align-items: center;
    color: white !important;
}

.editor-tabs {
    display: flex;
    gap: 0.5rem;
}

.editor-tab {
    padding: 0.5rem 1rem;
    background: rgba(255, 255, 255, 0.1) !important;
    border: 1px solid rgba(255, 255, 255, 0.2) !important;
    border-radius: 10px !important;
    cursor: pointer;
    transition: all 0.3s ease;
    color: rgba(255, 255, 255, 0.8) !important;
}

.editor-tab.active {
    background: linear-gradient(135deg, rgba(100, 150, 255, 0.8), rgba(0, 212, 255, 0.8)) !important;
    color: white !important;
    border-color: rgba(255, 255, 255, 0.3) !important;
}

.editor-tab:hover:not(.active) {
    background: rgba(100, 150, 255, 0.3) !important;
    color: white !important;
    transform: translateY(-1px);
}

.editor-content {
    position: relative;
}

.code-editor {
    width: 100%;
    min-height: 400px;
    border: none;
    outline: none;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    font-size: 14px;
    line-height: 1.5;
    padding: 1rem;
    resize: vertical;
    background: rgba(45, 55, 85, 0.4) !important;
    color: rgba(255, 255, 255, 0.9) !important;
    border-radius: 0 0 15px 15px;
}

.code-editor:focus {
    box-shadow: inset 0 0 10px rgba(100, 150, 255, 0.3);
}

.code-preview {
    padding: 1rem;
    background: rgba(45, 55, 85, 0.4) !important;
    min-height: 400px;
    overflow: auto;
    color: rgba(255, 255, 255, 0.9) !important;
    border-radius: 0 0 15px 15px;
}

/* 统一预览模式的Prism样式与编辑器风格 */
.code-preview pre {
    background: transparent !important;
    margin: 0 !important;
    padding: 0 !important;
    border: none !important;
    border-radius: 0 !important;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace !important;
    font-size: 14px !important;
    line-height: 1.5 !important;
    color: rgba(255, 255, 255, 0.9) !important;
}

.code-preview code {
    background: transparent !important;
    color: rgba(255, 255, 255, 0.9) !important;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace !important;
    font-size: 14px !important;
    line-height: 1.5 !important;
}

/* 覆盖Prism深色主题的颜色，使其与编辑器一致 */
.code-preview .token.comment,
.code-preview .token.prolog,
.code-preview .token.doctype,
.code-preview .token.cdata {
    color: rgba(255, 255, 255, 0.5) !important;
}

.code-preview .token.punctuation {
    color: rgba(255, 255, 255, 0.7) !important;
}

.code-preview .token.property,
.code-preview .token.tag,
.code-preview .token.boolean,
.code-preview .token.number,
.code-preview .token.constant,
.code-preview .token.symbol,
.code-preview .token.deleted {
    color: rgba(100, 150, 255, 0.9) !important;
}

.code-preview .token.selector,
.code-preview .token.attr-name,
.code-preview .token.string,
.code-preview .token.char,
.code-preview .token.builtin,
.code-preview .token.inserted {
    color: rgba(0, 212, 255, 0.9) !important;
}

.code-preview .token.operator,
.code-preview .token.entity,
.code-preview .token.url,
.code-preview .language-css .token.string,
.code-preview .style .token.string {
    color: rgba(255, 255, 255, 0.8) !important;
}

.code-preview .token.atrule,
.code-preview .token.attr-value,
.code-preview .token.keyword {
    color: rgba(255, 100, 150, 0.9) !important;
}

.code-preview .token.function,
.code-preview .token.class-name {
    color: rgba(150, 255, 100, 0.9) !important;
}

.code-preview .token.regex,
.code-preview .token.important,
.code-preview .token.variable {
    color: rgba(255, 200, 100, 0.9) !important;
}

.file-info {
    background: linear-gradient(135deg, rgba(45, 55, 85, 0.3) 0%, rgba(35, 45, 75, 0.4) 100%) !important;
    padding: 1rem;
    border-radius: 15px !important;
    margin-bottom: 1rem;
    border: 2px solid rgba(100, 150, 255, 0.5);
    backdrop-filter: blur(15px);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3), 0 0 20px rgba(100, 150, 255, 0.2);
    color: rgba(255, 255, 255, 0.9) !important;
}

.file-stats {
    display: flex;
    gap: 2rem;
    margin-top: 0.5rem;
}

.file-stat {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    color: rgba(255, 255, 255, 0.7) !important;
    font-size: 0.875rem;
}

.path-input {
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    font-size: 0.875rem;
}

.editor-actions {
    display: flex;
    gap: 0.5rem;
    align-items: center;
}

.line-numbers {
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    width: 4rem;
    background: rgba(45, 55, 85, 0.4) !important;
    border-right: 1px solid rgba(100, 150, 255, 0.5) !important;
    padding: 1rem 0.5rem;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    font-size: 14px;
    line-height: 1.5;
    color: rgba(255, 255, 255, 0.5) !important;
    user-select: none;
    overflow: hidden;
    text-align: right;
    z-index: 1;
}

.code-editor-with-numbers {
    padding-left: 5rem;
}

/* 确保代码编辑器有正确的左边距 */
#editTab .form-control {
    padding-left: 5rem !important;
    position: relative;
    z-index: 2;
}

#editTab {
    position: relative;
}

.validation-info {
    margin-top: 1rem;
    padding: 1rem;
    background: linear-gradient(135deg, rgba(23, 162, 184, 0.2), rgba(0, 212, 255, 0.2)) !important;
    border-radius: 15px !important;
    border-left: 4px solid rgba(0, 212, 255, 0.8) !important;
    color: rgba(255, 255, 255, 0.9) !important;
    backdrop-filter: blur(10px);
}

.keyboard-shortcuts {
    margin-top: 1rem;
    padding: 1rem;
    background: linear-gradient(135deg, rgba(0, 0, 0, 0.8) 0%, rgba(30, 30, 60, 0.9) 100%) !important;
    border-radius: 15px !important;
    border: 2px solid rgba(100, 150, 255, 0.5);
    backdrop-filter: blur(15px);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3), 0 0 20px rgba(100, 150, 255, 0.2);
    color: rgba(255, 255, 255, 0.9) !important;
}

.shortcut-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 0.25rem;
}

.shortcut-key {
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    background: rgba(100, 150, 255, 0.3) !important;
    padding: 0.125rem 0.375rem;
    border-radius: 8px !important;
    font-size: 0.75rem;
    color: white !important;
    border: 1px solid rgba(255, 255, 255, 0.2);
}

/* 卡片样式 */
.card {
    background: linear-gradient(135deg, rgba(0, 0, 0, 0.8) 0%, rgba(30, 30, 60, 0.9) 100%) !important;
    border: 2px solid rgba(100, 150, 255, 0.5) !important;
    border-radius: 15px !important;
    backdrop-filter: blur(15px);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3), 0 0 20px rgba(100, 150, 255, 0.2);
}

.card-header {
    background: linear-gradient(135deg, rgba(100, 150, 255, 0.8), rgba(0, 212, 255, 0.8)) !important;
    border-bottom: 1px solid rgba(255, 255, 255, 0.2) !important;
    color: white !important;
    border-radius: 13px 13px 0 0 !important;
}

.card-body {
    color: rgba(255, 255, 255, 0.9) !important;
}

/* 按钮样式 */
.btn {
    border-radius: 10px !important;
    font-weight: 600;
    transition: all 0.3s ease;
}

.btn-primary {
    background: linear-gradient(135deg, rgba(100, 150, 255, 0.8), rgba(0, 212, 255, 0.8)) !important;
    border: 2px solid rgba(255, 255, 255, 0.3) !important;
    color: white !important;
}

.btn-primary:hover {
    background: linear-gradient(135deg, rgba(100, 150, 255, 1), rgba(0, 212, 255, 1)) !important;
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(100, 150, 255, 0.4);
}

.btn-success {
    background: linear-gradient(135deg, rgba(40, 167, 69, 0.8), rgba(0, 212, 255, 0.8)) !important;
    border: 2px solid rgba(255, 255, 255, 0.3) !important;
    color: white !important;
}

.btn-success:hover {
    background: linear-gradient(135deg, rgba(40, 167, 69, 1), rgba(0, 212, 255, 1)) !important;
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(40, 167, 69, 0.4);
}

.btn-secondary {
    background: linear-gradient(135deg, rgba(108, 117, 125, 0.8), rgba(60, 60, 80, 0.8)) !important;
    border: 2px solid rgba(255, 255, 255, 0.3) !important;
    color: white !important;
}

.btn-secondary:hover {
    background: linear-gradient(135deg, rgba(108, 117, 125, 1), rgba(60, 60, 80, 1)) !important;
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(108, 117, 125, 0.4);
}

.btn-outline-secondary {
    background: rgba(255, 255, 255, 0.1) !important;
    border: 1px solid rgba(100, 150, 255, 0.5) !important;
    color: rgba(255, 255, 255, 0.9) !important;
}

.btn-outline-secondary:hover {
    background: rgba(100, 150, 255, 0.3) !important;
    color: white !important;
    transform: translateY(-1px);
}

/* 文本样式 */
h4, h5, .form-label {
    color: rgba(255, 255, 255, 0.9) !important;
}

.text-muted {
    color: rgba(255, 255, 255, 0.5) !important;
}

.form-text {
    color: rgba(255, 255, 255, 0.6) !important;
}

.text-danger {
    color: rgba(255, 100, 100, 0.9) !important;
}

/* 表单控件样式 */
.form-control, .form-select {
    background: rgba(45, 55, 85, 0.4) !important;
    border: 2px solid rgba(100, 150, 255, 0.5) !important;
    color: rgba(255, 255, 255, 0.9) !important;
    border-radius: 10px !important;
}

.form-control:focus, .form-select:focus {
    background: rgba(45, 55, 85, 0.6) !important;
    border-color: rgba(100, 150, 255, 0.8) !important;
    box-shadow: 0 0 15px rgba(100, 150, 255, 0.3) !important;
    color: white !important;
}

.form-control::placeholder {
    color: rgba(255, 255, 255, 0.5) !important;
}

.form-check-input {
    background: rgba(45, 55, 85, 0.4) !important;
    border: 2px solid rgba(100, 150, 255, 0.5) !important;
}

.form-check-input:checked {
    background: linear-gradient(135deg, rgba(100, 150, 255, 0.8), rgba(0, 212, 255, 0.8)) !important;
    border-color: rgba(255, 255, 255, 0.3) !important;
}

.form-check-label {
    color: rgba(255, 255, 255, 0.9) !important;
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid mt-4">
    <div class="row">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">
                    <h4 class="mb-0">
                        {% if file_obj %}
                            <i class="fas fa-edit"></i> 编辑文件
                        {% else %}
                            <i class="fas fa-plus"></i> 创建新文件
                        {% endif %}
                        <span class="text-muted">- {{ code.title }}</span>
                    </h4>
                </div>
                <div class="card-body">
                    <form method="post" id="fileForm">
                        {% csrf_token %}
                        
                        <!-- 文件路径 -->
                        <div class="mb-3">
                            <label for="{{ form.file_path.id_for_label }}" class="form-label">
                                <i class="fas fa-folder-open"></i> 文件路径
                            </label>
                            {{ form.file_path }}
                            {% if form.file_path.help_text %}
                                <div class="form-text">{{ form.file_path.help_text }}</div>
                            {% endif %}
                            {% if form.file_path.errors %}
                                <div class="text-danger">
                                    {% for error in form.file_path.errors %}
                                        <small>{{ error }}</small>
                                    {% endfor %}
                                </div>
                            {% endif %}
                        </div>
                        

                        
                        <!-- 编辑器 -->
                        <div class="editor-container">
                            <div class="editor-header">
                                <div class="editor-tabs">
                                    <button type="button" class="editor-tab active" data-tab="edit">
                                        <i class="fas fa-code"></i> 编辑
                                    </button>
                                    <button type="button" class="editor-tab" data-tab="preview">
                                        <i class="fas fa-eye"></i> 预览
                                    </button>
                                </div>
                                <div class="editor-actions">
                                </div>
                            </div>
                            
                            <div class="editor-content">
                                <!-- 编辑模式 -->
                                <div id="editTab" class="tab-content">
                                    <div class="line-numbers" id="lineNumbers"></div>
                                    {{ form.content }}
                                </div>
                                
                                <!-- 预览模式 -->
                                <div id="previewTab" class="tab-content code-preview" style="display: none;">
                                    <pre><code id="previewCode" class="language-python"></code></pre>
                                </div>
                            </div>
                        </div>
                        
                        {% if form.content.errors %}
                            <div class="text-danger mt-2">
                                {% for error in form.content.errors %}
                                    <small>{{ error }}</small>
                                {% endfor %}
                            </div>
                        {% endif %}
                        
                        <!-- 表单错误 -->
                        {% if form.non_field_errors %}
                            <div class="alert alert-danger mt-3">
                                {% for error in form.non_field_errors %}
                                    {{ error }}
                                {% endfor %}
                            </div>
                        {% endif %}
                        
                        <!-- 提交按钮 -->
                        <div class="d-flex justify-content-between mt-3">
                            <a href="{% url 'codes:code_files' code.id %}" class="btn btn-secondary">
                                <i class="fas fa-arrow-left"></i> 返回
                            </a>
                            <div>
                                <button type="button" class="btn btn-outline-primary" id="saveAndContinue">
                                    <i class="fas fa-save"></i> 保存并继续
                                </button>
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-check"></i> 保存
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <!-- 侧边栏 -->
        <div class="col-md-4">
            <!-- 文件信息 -->
            {% if file_obj %}
            <div class="file-info">
                <h6><i class="fas fa-info-circle"></i> 文件信息</h6>
                <div class="file-stats">
                    <div class="file-stat">
                        <i class="fas fa-calendar"></i>
                        <span>{{ file_obj.created_at|date:"Y-m-d H:i" }}</span>
                    </div>
                    <div class="file-stat">
                        <i class="fas fa-weight-hanging"></i>
                        <span id="fileSize">{{ file_obj.file_size }} 字节</span>
                    </div>
                </div>
                <div class="file-stats">
                    <div class="file-stat">
                        <i class="fas fa-edit"></i>
                        <span>{{ file_obj.updated_at|date:"Y-m-d H:i" }}</span>
                    </div>
                    <div class="file-stat">
                        <i class="fas fa-file-code"></i>
                        <span id="lineCount">0 行</span>
                    </div>
                </div>
            </div>
            {% endif %}
            
            <!-- 验证信息 -->
            <div class="validation-info">
                <h6><i class="fas fa-check-circle"></i> 验证规则</h6>
                <ul class="mb-0">
                    <li>文件路径不能为空</li>
                    <li>文件路径必须唯一</li>
                    <li>仅支持 .py、.js、.ts 文件格式</li>
                    <li>文件内容不能超过 100KB</li>
                    <li>所有文件为同级结构，系统会根据战斗需要调用相应文件</li>
                </ul>
            </div>
            
            <!-- 快捷键 -->
            <div class="keyboard-shortcuts">
                <h6><i class="fas fa-keyboard"></i> 快捷键</h6>
                <div class="shortcut-item">
                    <span>保存</span>
                    <span class="shortcut-key">Ctrl + S</span>
                </div>
                <div class="shortcut-item">
                    <span>格式化</span>
                    <span class="shortcut-key">Ctrl + Shift + F</span>
                </div>
                <div class="shortcut-item">
                    <span>查找</span>
                    <span class="shortcut-key">Ctrl + F</span>
                </div>
                <div class="shortcut-item">
                    <span>切换预览</span>
                    <span class="shortcut-key">Ctrl + Shift + P</span>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-core.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/autoloader/prism-autoloader.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const contentTextarea = document.getElementById('id_content');
    const filePathInput = document.getElementById('id_file_path');
    const lineNumbers = document.getElementById('lineNumbers');
    // editorStats 元素已移除
    const previewCode = document.getElementById('previewCode');
    const fileSize = document.getElementById('fileSize');
    const lineCount = document.getElementById('lineCount');
    
    // 添加样式类
    contentTextarea.classList.add('code-editor', 'code-editor-with-numbers');
    filePathInput.classList.add('form-control', 'path-input');
    
    // 标签切换
    document.querySelectorAll('.editor-tab').forEach(tab => {
        tab.addEventListener('click', function() {
            const tabName = this.dataset.tab;
            switchTab(tabName);
        });
    });
    
    function switchTab(tabName) {
        // 更新标签状态
        document.querySelectorAll('.editor-tab').forEach(tab => {
            tab.classList.remove('active');
        });
        document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');
        
        // 切换内容
        document.querySelectorAll('.tab-content').forEach(content => {
            content.style.display = 'none';
        });
        
        if (tabName === 'edit') {
            document.getElementById('editTab').style.display = 'block';
        } else if (tabName === 'preview') {
            document.getElementById('previewTab').style.display = 'block';
            updatePreview();
        }
    }
    
    function updatePreview() {
        const content = contentTextarea.value;
        const language = getLanguageFromPath(filePathInput.value);
        
        previewCode.className = `language-${language}`;
        previewCode.textContent = content;
        
        // 重新高亮
        Prism.highlightElement(previewCode);
    }
    
    function getLanguageFromPath(path) {
        const ext = path.split('.').pop().toLowerCase();
        const langMap = {
            'py': 'python',
            'js': 'javascript',
            'java': 'java',
            'cpp': 'cpp',
            'c': 'c',
            'h': 'c',
            'hpp': 'cpp',
            'html': 'html',
            'css': 'css',
            'json': 'json',
            'xml': 'xml',
            'yaml': 'yaml',
            'yml': 'yaml',
            'md': 'markdown'
        };
        return langMap[ext] || 'text';
    }
    
    // 行号更新
    function updateLineNumbers() {
        const lines = contentTextarea.value.split('\n');
        const lineNumbersHtml = lines.map((_, index) => index + 1).join('<br>');
        lineNumbers.innerHTML = lineNumbersHtml;
        
        // 更新统计信息
        updateStats();
    }
    
    function updateStats() {
        const content = contentTextarea.value;
        const lines = content.split('\n');
        // 行列显示已移除
        
        if (lineCount) {
            lineCount.textContent = `${lines.length} 行`;
        }
        
        if (fileSize) {
            const bytes = new Blob([content]).size;
            fileSize.textContent = `${bytes} 字节`;
        }
    }
    
    // 事件监听
    contentTextarea.addEventListener('input', updateLineNumbers);
    contentTextarea.addEventListener('scroll', function() {
        lineNumbers.scrollTop = this.scrollTop;
    });
    contentTextarea.addEventListener('click', updateStats);
    contentTextarea.addEventListener('keyup', updateStats);
    
    // 初始化
    updateLineNumbers();
    

    
    // 快捷键
    contentTextarea.addEventListener('keydown', function(e) {
        if (e.ctrlKey) {
            switch(e.key) {
                case 's':
                    e.preventDefault();
                    document.getElementById('fileForm').submit();
                    break;

                case 'p':
                    if (e.shiftKey) {
                        e.preventDefault();
                        const activeTab = document.querySelector('.editor-tab.active').dataset.tab;
                        switchTab(activeTab === 'edit' ? 'preview' : 'edit');
                    }
                    break;
            }
        }
        
        // Tab 键处理
        if (e.key === 'Tab') {
            e.preventDefault();
            const start = this.selectionStart;
            const end = this.selectionEnd;
            
            if (e.shiftKey) {
                // Shift+Tab: 减少缩进
                const beforeCursor = this.value.substring(0, start);
                const lineStart = beforeCursor.lastIndexOf('\n') + 1;
                const lineContent = this.value.substring(lineStart, end);
                
                if (lineContent.startsWith('    ')) {
                    this.value = this.value.substring(0, lineStart) + 
                                lineContent.substring(4) + 
                                this.value.substring(end);
                    this.selectionStart = this.selectionEnd = start - 4;
                }
            } else {
                // Tab: 增加缩进
                this.value = this.value.substring(0, start) + 
                            '    ' + 
                            this.value.substring(end);
                this.selectionStart = this.selectionEnd = start + 4;
            }
            
            updateLineNumbers();
        }
    });
    
    // 保存并继续
    document.getElementById('saveAndContinue').addEventListener('click', function() {
        const form = document.getElementById('fileForm');
        const formData = new FormData(form);
        formData.append('save_and_continue', '1');
        
        fetch(form.action, {
            method: 'POST',
            body: formData,
            headers: {
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 显示保存成功消息
                const alert = document.createElement('div');
                alert.className = 'alert alert-success alert-dismissible fade show';
                alert.innerHTML = `
                    <i class="fas fa-check"></i> 文件已保存
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                `;
                form.insertBefore(alert, form.firstChild);
                
                // 3秒后自动消失
                setTimeout(() => {
                    alert.remove();
                }, 3000);
            } else {
                // 显示错误消息
                console.error('保存失败:', data.errors);
            }
        })
        .catch(error => {
            console.error('保存失败:', error);
        });
    });
});
</script>
{% endblock %}